#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import json
from json import JSONDecodeError

from logger import logger


class Analysis:
    """
    Package change difference point analysis and change impact scope analysis classes
    """

    def __init__(self, diff_file):
        self.diff_file = diff_file

    def depended_analysis(self):
        """
        According to the change points analyzed by the _diff_analysis method,
        the compilation and installation dependencies of the package are analyzed.
        """
        diff_analysis_result = self._diff_analysis()
        pass

    def _diff_analysis(self):
        """
        Analyze the package changes and return to the change points that need to continue to be verified
        :return Analysis results, e.g.:
        {
            "need_analysis": true,
            "analysis_content": {
                "rpmA": {
                    "changed_provides": [
                        "componment1",
                        "componment2"
                    ],
                    "abi_change_effect": [
                        "rpm1",
                        "rpm2",
                        "rpm3"
                    ]
                }
            }
        }
        """
        analysis_result = dict(analysis_content={}, need_analysis=False)
        with open(self.diff_file, 'r') as df:
            try:
                compare_result = json.load(df)
                diff_content = compare_result.get('compare_details').get('diff').get('diff_details')
            except (JSONDecodeError, AttributeError) as error:
                logger.error(f"Failed to parse the package change result file {self.diff_file}, message is:{error}")
                return analysis_result

        if not diff_content:
            logger.info("No changes to the package")
            return analysis_result

        for rpm_name, rpm_diff in diff_content.items():
            rpm_provide_diff = rpm_diff.get("rpm provides").get("less", [])
            rpm_abi_effect = rpm_diff.get("rpm symbol").get("total_effect_other_rpm", [])
            if any([rpm_provide_diff, rpm_abi_effect]):
                analysis_result[rpm_name] = dict(changed_provides=rpm_provide_diff, abi_change_effect=rpm_abi_effect)

        return analysis_result
